package com.finn.domain.user.service;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.finn.domain.user.entity.User;
import com.finn.domain.user.entity.table.UserTableDef;
import com.finn.domain.user.repository.UserMapper;
import com.finn.infrastructure.util.VerificationCodeUtil;
import com.finn.interfaces.dto.CheckCodeDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * accountDomainService.
 *
 * @author Li Zemin
 * @since 2023/6/27 17:38
 */
@Slf4j
@Service
public class UserDomainService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	StringRedisTemplate redisTemplate;

	public User getUserByUid(String uid) {
		return this.userMapper.selectOneByCondition(UserTableDef.USER.UID.eq(uid));
	}

	@Transactional
	@SuppressWarnings("DLS_DEAD_LOCAL_STORE")
	public User createUser(User user) {
		this.userMapper.insertOrUpdate(user);
		return user;
	}

	public String generateCode(String phoneNumber) {
		String code = VerificationCodeUtil.generateVerificationCode();
		// TODO 开发阶段写死 000000
		code = "000000";
		this.redisTemplate.opsForValue().set("generate:verification:code:" + phoneNumber, code, 5, TimeUnit.MINUTES);
		return code;
	}

	public Boolean checkCode(CheckCodeDTO codeDTO) {
		String code = this.redisTemplate.opsForValue().get("generate:verification:code:" + codeDTO.getPhoneNumber());
		if (StringUtils.isNotBlank(code) && code.equals(codeDTO.getCode())) {
			return true;
		}
		return false;
	}

}
